# -*- coding: utf-8 -*-
import hashlib
import uuid
from tkinter import Image

import view as view
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.urls import reverse

from apis.forms import AvatarUploadForm
from apis.models import UserProfile

__author__ = 'JK'
__date__ = '2019/4/12 0:04'

import os
from django.http import HttpResponse, Http404, FileResponse, JsonResponse, HttpResponseRedirect
from LitterProject import settings
from utils import responses
from django.views import View


def image(request):
    if request.method == 'GET':
        name = request.GET.get('name')
        imgfile = os.path.join(str(settings.IMAGES_DIR), str(name) + '.jpg')
        if not os.path.exists(imgfile):
            return Http404
        else:
            data = open(imgfile, 'rb').read()
            return HttpResponse(content=data, content_type='image/jpg')
            # return FileResponse(open(imgfile, 'rb'), content_type='image/jpg')


class ImageView(View, responses.CommonResponseMixin):
    def get(self, request):
        name = request.GET.get('name')
        imgfile = os.path.join(str(settings.IMAGES_DIR), str(name) + '.jpg')
        if os.path.exists(imgfile):
            data = open(imgfile, 'rb').read()
            return HttpResponse(content=data, content_type='image/jpg')
        else:
            response = self.wrap_json_response(code=responses.ReturnCode.FAILED)
            return JsonResponse(data=response, safe=False, json_dumps_params={'ensure_ascii': False})

    def post(self, request):
        # name = request.get('name')
        # img = request.FILES['file']
        # path = os.path.join(settings.IMAGES_DIR, str(name) + '.jpg')
        # with open(path, 'wb') as f:
        #     for chunk in img.chunks():
        #         f.write(chunk)
        # response = self.wrap_json_response(code=responses.ReturnCode.SUCCESS)
        # return JsonResponse(data=response, safe=False, json_dumps_params={'ensure_ascii':False})

        files = request.FILES
        name = request.GET.get('name')
        response = []
        for key, value in files.items():
            content = value.read()
            path = os.path.join(settings.IMAGES_DIR, str(name) + '.jpg')
            with open(path, 'wb') as f:
                f.write(content)
            response.append({
                'name': key,
                'url': path
            })
        response = self.wrap_json_response(data=response, code=responses.ReturnCode.SUCCESS)
        return JsonResponse(data=response, safe=False, json_dumps_params={'ensure_ascii': False})

    def delete(self, request):
        name = request.GET.get('name')
        img_name = name + '.jpg'
        path = os.path.join(str(settings.IMAGES_DIR), img_name)
        if os.path.exists(path):
            os.remove(path)
            message = 'jpg remove success'
        else:
            message = 'file (%s) not found' % img_name
        response = self.wrap_json_response(code=responses.ReturnCode.SUCCESS, message=message)
        return JsonResponse(data=response, safe=False, json_dumps_params={'ensure_ascii': False})


def image_text(request):
    if request.method == 'GET':
        name = request.GET.get('name')
        imgfile = os.path.join(str(settings.IMAGES_DIR), str(name) + '.jpg')
        if not os.path.exists(imgfile):
            # print(imgfile)
            return JsonResponse(responses.wrap_json_response(code=responses.ReturnCode.FAILED))
        else:
            response_data = {}
            response_data['name'] = name + '.jpg'
            response_data['url'] = '/service/image?name=%s' % (name)
            response = responses.wrap_json_response(data=response_data)
            return JsonResponse(data=response, safe=False, json_dumps_params={'ensure_ascii': False})


# @login_required
# def ajax_avatar_upload(request):
#     user = request.user
#     user_profile = get_object_or_404(UserProfile, user=user)
#
#     if request.method == "POST":
#         form = AvatarUploadForm(request.POST, request.FILES)
#     if form.is_valid():
#         img = request.FILES['avatar_file'] # 获取上传图片
#         cropped_avatar = crop_image(img, user.id)
#         user_profile.avatar = cropped_avatar # 将图片路径修改到当前会员数据库
#         user_profile.save()
#         return HttpResponseRedirect(reverse('myaccount:profile'))
#
# def crop_image(file, uid):
#     # 随机生成新的图片名，自定义路径。
#     ext = file.name.split('.')[-1]
#     file_name = '{}.{}'.format(uuid.uuid4().hex[:10], ext)
#     cropped_avatar = os.path.join(uid, "avatar", file_name)
#     # 相对根目录路径
#     file_path = os.path.join("media", uid, "avatar", file_name)
#
#     # 裁剪图片,压缩尺寸为200*200。
#     img = Image.open(file)
#     crop_im = img.crop((50, 50, 300, 300)).resize((200, 200), Image.ANTIALIAS)
#     crop_im.save(file_path)
#
#     return cropped_avatar
